import os
import re
from main_batch import main


def extract_number_from_chapter(chapter_name):
    """从章节名称中提取末尾的数字"""
    # 查找下划线后面的数字
    match = re.search(r'_(\d+)$', chapter_name)
    if match:
        return int(match.group(1))
    # 如果没有数字，返回一个大值让它排在后面
    return float('inf')


def read_all_books(books_dir="books"):
    """
    读取books目录下所有书籍的所有章节内容，并按章节编号数值排序

    参数:
        books_dir: 书籍根目录，默认为"books"

    返回:
        一个字典，结构为{书名: {章节名: 内容}}，其中章节按编号数值排序
    """
    # 检查books目录是否存在
    if not os.path.exists(books_dir):
        print(f"错误: 目录 '{books_dir}' 不存在")
        return {}

    if not os.path.isdir(books_dir):
        print(f"错误: '{books_dir}' 不是一个目录")
        return {}

    all_books = {}

    # 遍历books目录下的所有书籍文件夹（按文件夹名排序）
    for book_folder in sorted(os.listdir(books_dir)):
        book_path = os.path.join(books_dir, book_folder)

        # 只处理目录（每个目录代表一本书）
        if os.path.isdir(book_path):
            book_name = book_folder  # 用书文件夹名作为书名
            chapters = {}

            # 获取该书籍下的所有txt文件
            chapter_files = [f for f in os.listdir(book_path)
                             if os.path.isfile(os.path.join(book_path, f))
                             and f.lower().endswith('.txt')]

            # 按章节文件名中的数字值排序
            sorted_chapters = sorted(
                chapter_files,
                key=lambda x: extract_number_from_chapter(os.path.splitext(x)[0])
            )

            # 读取每个章节的内容
            for chapter_file in sorted_chapters:
                chapter_path = os.path.join(book_path, chapter_file)
                chapter_name = os.path.splitext(chapter_file)[0]  # 去除.txt后缀

                try:
                    # 尝试以UTF-8编码读取
                    with open(chapter_path, 'r', encoding='utf-8') as f:
                        content = f.read()
                        chapters[chapter_name] = content
                        # print(f"已读取: {book_name} - {chapter_name}")
                except UnicodeDecodeError:
                    # 尝试GBK编码
                    try:
                        with open(chapter_path, 'r', encoding='gbk') as f:
                            content = f.read()
                            chapters[chapter_name] = content
                            # print(f"已读取: {book_name} - {chapter_name} (使用GBK编码)")
                    except Exception as e:
                        print(f"读取 {book_name} - {chapter_file} 失败: {str(e)}")
                except Exception as e:
                    print(f"读取 {book_name} - {chapter_file} 失败: {str(e)}")

            if chapters:  # 只有当有章节内容时才添加这本书
                all_books[book_name] = chapters

    return all_books


def display_books(books_content):
    """展示所有书籍及其章节内容"""
    if not books_content:
        print("没有找到任何书籍内容")
        return

    print("\n" + "=" * 50)
    print("书籍内容展示")
    print("=" * 50 + "\n")

    for book_name, chapters in books_content.items():
        print(f"📚 书籍: {book_name}")
        print(f"   章节数量: {len(chapters)}")
        print("   章节列表:")

        for i, (chapter_name, content) in enumerate(chapters.items(), 1):
            print(f"\n   {i}. 章节: {chapter_name}")
            # print("   " + "-" * 40)
            # 只显示前300个字符，避免输出过长
            # preview = content[:300].replace("\n", " ")
            # 批量创建视频
            main(book_name, chapter_name, content.replace('*', ''))

            # print(f"   内容预览: {preview}...")
            # print("   " + "-" * 40)

        # print("\n" + "=" * 50 + "\n")


if __name__ == "__main__":
    # 读取所有书籍内容
    books_content = read_all_books()

    # 显示统计信息
    print("\n读取完成!")
    print(f"共发现 {len(books_content)} 本书")

    total_chapters = 0
    for chapters in books_content.values():
        total_chapters += len(chapters)
    print(f"共读取 {total_chapters} 个章节")

    # 展示书籍内容（按顺序）
    display_books(books_content)
